//
//  LoginViewController.m
//  Gruphoto
//
//  Created by Thao Nguyen Huy on 1/3/13.
//  Copyright (c) 2013 CNC Software. All rights reserved.
//

#import "LoginViewController.h"
#import "GruphotoTabBarController.h"
#import "GruphotoAppDelegate.h"
#import "User.h"

#define kEmailIndex     0
#define kPasswordIndex  1
#define kForgotPassword 2

@interface LoginViewController (PrivateMethods)
- (void)resignKeyboard;
@end

@implementation LoginViewController

@synthesize loginYourAccountLabel, forgotYourPasswordLabel;
@synthesize emailTextField, passwordTextField, passwordRecipient;

#pragma mark - View lifecycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {       
        UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [cancelButton setBounds:CGRectMake(0, 0, 51, 30)];
        [cancelButton setBackgroundImage:[UIImage imageNamed:@"button_cancel.png"] forState:UIControlStateNormal];
        [cancelButton addTarget:self action:@selector(cancelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *cancelButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cancelButton];
        self.navigationItem.leftBarButtonItem = cancelButtonItem;
        [cancelButtonItem release];
        
        UIButton *loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [loginButton setBounds:CGRectMake(0, 0, 51, 30)];
        [loginButton setBackgroundImage:[UIImage imageNamed:@"button_login_blue.png"] forState:UIControlStateNormal];
        [loginButton addTarget:self action:@selector(loginButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *loginButtonItem = [[UIBarButtonItem alloc] initWithCustomView:loginButton];
        self.navigationItem.rightBarButtonItem = loginButtonItem;
        [loginButtonItem release];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:226/255.0 green:231/255.0 blue:237/255.0 alpha:1.0];
    loginYourAccountLabel.textColor = [UIColor colorWithRed:50/255.0 green:57/255.0 blue:62/255.0 alpha:1.0];
    forgotYourPasswordLabel.textColor = [UIColor colorWithRed:71/255.0 green:138/255.0 blue:179/255.0 alpha:1.0];
    self.passwordRecipient = @"";
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.loginYourAccountLabel = nil;
    self.forgotYourPasswordLabel = nil;
    self.emailTextField = nil;
    self.passwordTextField = nil;
}

- (void)dealloc {
    self.passwordRecipient = nil;
    [loginYourAccountLabel release];
    [forgotYourPasswordLabel release];
    [emailTextField release];
    [passwordTextField release];
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Private methods
- (void)resignKeyboard {
    [emailTextField resignFirstResponder];
    [passwordTextField resignFirstResponder];
}

#pragma mark - Action methods
- (IBAction)cancelButtonPressed:(id)sender {
    [self resignKeyboard];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)loginButtonPressed:(id)sender {
    if (emailTextField.text.length == 0) {
        emailTextField.text = @"thebluez@cnc.vn";
        passwordTextField.text = @"z";        
    }
    
//    emailTextField.text = @"truonggru@cnc.com";
//    passwordTextField.text = @"grupt";
    
    [self resignKeyboard];
    
    // Validate data
    NSString *email = emailTextField.text;
    NSString *password = passwordTextField.text;
    
    NSString *errorMessage = nil;
    NSInteger tag = 0;
    
    if (email.length == 0) {
        errorMessage = NSLocalizedString(@"Please enter your email", @"");
        tag = AlertViewTagEmailMissing;
    }
    else if (![Global isValidEmail:email]) {
        errorMessage = NSLocalizedString(@"Email is invalid", @"");
        tag = AlertViewTagEmailInvalid;
    }
    else if (password.length == 0) {
        errorMessage = NSLocalizedString(@"Please enter your password", @"");
        tag = AlertViewTagPasswordMissing;
    }
    
    if (errorMessage != nil) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error message", @"")
                                                            message:errorMessage
                                                           delegate:self
                                                  cancelButtonTitle:NSLocalizedString(@"OK", @"")
                                                  otherButtonTitles:nil];
        alertView.tag = tag;
        [alertView show];
        [alertView release];
        return;
    }

    
    [[GruphotoAppDelegate sharedDelegate] showHUDWithStatus:@"Logging in..."];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:email forKey:kEmail];
    [params setObject:password forKey:kPassword];
    NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:kDeviceToken];
    [params setObject:deviceToken forKey:kDeviceToken];
    [TNHRequestHelper sendPostRequest:kLoginWithAppAccountUrl
                              withTag:RequestTagLoginAppAccount
                               params:params
                             delegate:self];
}

- (IBAction)forgotPasswordButtonPressed:(id)sender {
    [self resignKeyboard];
    UIAlertView *alertView;
    UITextField *emailField;
    NSString *message;
    
    alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Forgot your password?", @"")
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:NSLocalizedString(@"Cancel", @"")
                                              otherButtonTitles:NSLocalizedString(@"Submit", @""), nil];
    if ([Global systemVersion] >= 5.0) {
        alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
        emailField = [alertView textFieldAtIndex:0];
        message = NSLocalizedString(@"Enter your registered email address and we’ll send your pasword", @"");
    }
    else {
        emailField = [[[UITextField alloc] initWithFrame:CGRectMake(12, 90, 260, 30)] autorelease];
        emailField.borderStyle = UITextBorderStyleRoundedRect;            
        [alertView addSubview:emailField];
        message = NSLocalizedString(@"Enter your registered email address and we’ll send your pasword\n\n", @"");
    }
    
    emailField.placeholder = @"example@gruphoto.com";
    emailField.clearButtonMode = UITextFieldViewModeAlways;
    emailField.keyboardType = UIKeyboardTypeEmailAddress;
    emailField.font = [UIFont systemFontOfSize:17];
    emailField.returnKeyType = UIReturnKeyDone;
    emailField.delegate = self;
    emailField.tag = kForgotPassword;
    emailField.text = passwordRecipient;
    [emailField becomeFirstResponder];
    
    alertView.tag = AlertViewTagForgotPassword;
    alertView.message = message;
    [alertView show];
    [alertView release];
}


#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    switch (textField.tag) {
        case kEmailIndex:
            [passwordTextField becomeFirstResponder];
            break;
        case kPasswordIndex:
            [passwordTextField resignFirstResponder];
            [self loginButtonPressed:nil];
            break;
        case kForgotPassword: {
            UIAlertView *alertView = (UIAlertView *)textField.superview;
            [alertView dismissWithClickedButtonIndex:1 animated:YES];
            break;
        }
        default:
            break;
    }
    return YES;
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    NSLog(@"Button index: %d", buttonIndex);
    switch (alertView.tag) {
        case AlertViewTagEmailMissing:
        case AlertViewTagEmailInvalid:
            [emailTextField becomeFirstResponder];
            break;
        case AlertViewTagPasswordMissing:
            [passwordTextField becomeFirstResponder];
            break;
        case AlertViewTagForgotPassword: {
            if (buttonIndex == 0) {
                // do nothing
            }
            else {
                UITextField *textField = nil;
                for (UIView *view in alertView.subviews) {
                    if ([view isKindOfClass:[UITextField class]]) {
                        textField = (UITextField *)view;
                        break;
                    }
                }
                NSString *email = textField.text;
                self.passwordRecipient = email;
                if (email.length == 0) {
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Warning message"
                                                                        message:@"You must enter email"
                                                                       delegate:self
                                                              cancelButtonTitle:@"Cancel"
                                                              otherButtonTitles:@"Continue", nil];
                    alertView.tag = AlertViewTagEmailMissingInForgotPassword;
                    [alertView show];
                    [alertView release];
                }
                else {
                    if (![Global isValidEmail:email]) {
                        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Warning message"
                                                                            message:@"Email is invalid,\n please try again"
                                                                           delegate:self
                                                                  cancelButtonTitle:@"Cancel"
                                                                  otherButtonTitles:@"Continue", nil];
                        alertView.tag = AlertViewTagEmailMissingInForgotPassword;
                        [alertView show];
                        [alertView release];
                    }
                    else {
                        [[GruphotoAppDelegate sharedDelegate] showHUDWithStatus:@"Sending..."];
                        NSMutableDictionary *params = [NSMutableDictionary dictionary];
                        [params setObject:email forKey:kEmail];
                        [TNHRequestHelper sendPostRequest:kForgotPasswordUrl
                                                  withTag:RequestTagForgotPassword
                                                   params:params
                                                 delegate:self];    
                    }
                }
            }
            break;
        }
        case AlertViewTagEmailMissingInForgotPassword: {
            [self forgotPasswordButtonPressed:nil];
        }
        default:
            break;
    }
}

#pragma mark - ASIHTTPRequestDelegate
- (void)requestFinished:(ASIHTTPRequest *)request {
    [[GruphotoAppDelegate sharedDelegate] hideHUD];
    NSDictionary *response = (NSDictionary *)[TNHRequestHelper objectWithString:request.responseString];    
    if (request.tag == RequestTagLoginAppAccount) {
        NSInteger errorCode = [[response objectForKey:kErrorCode] integerValue];
        if (errorCode == ErrorCodeNone) {
            NSString *email = emailTextField.text;
            
            User *_loggedInUser = [[User alloc] init];
            _loggedInUser.email = email;
            if (![[response objectForKey:kFirstName] isEqual:[NSNull null]]) {
                _loggedInUser.firstName = [response objectForKey:kFirstName];
            }
            if (![[response objectForKey:kLastName] isEqual:[NSNull null]]) {
                _loggedInUser.lastName = [response objectForKey:kLastName];
            }
            if ([[response allKeys] containsObject:kPhone]) {
                if (![[response objectForKey:kPhone] isEqual:[NSNull null]]) {
                    _loggedInUser.phoneNumber = [response objectForKey:kPhone];
                }
            }
            _loggedInUser.numberOfPhotos = [[response objectForKey:kNumPhoto] integerValue];
            _loggedInUser.userId = [[response objectForKey:kUserId] integerValue];
            if (![[response objectForKey:kPhoto] isEqual:[NSNull null]]) {
                _loggedInUser.avatarUrl = [response objectForKey:kPhoto];
            }
            if (![[response objectForKey:kSocialId] isEqual:[NSNull null]]) {
                _loggedInUser.socialId = [response objectForKey:kSocialId];
            }
            _loggedInUser.token = [response objectForKey:kUserToken];
            _loggedInUser.numberOfLikes = [[response objectForKey:kNumLike] integerValue];
            _loggedInUser.numberOfFollowers = [[response objectForKey:kNumFollower] integerValue];
            [GruphotoAppDelegate sharedDelegate].loggedInUser = _loggedInUser;
            [_loggedInUser release];
            GruphotoTabBarController *tabbarController = [[GruphotoTabBarController alloc] init];
            [self presentModalViewController:tabbarController animated:YES];
            [tabbarController release];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
        else {
            NSString *errorMessage = [response objectForKey:kErrorMessage];
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Login error"
                                                                message:errorMessage
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
            [alertView show];
            [alertView release];
        }        
    }
    else if (request.tag == RequestTagForgotPassword) {
        NSInteger errorCode = [[response objectForKey:kErrorCode] integerValue];
        UIAlertView *alertView = nil;
        NSString *title = nil;
        NSString *message = nil;
        if (errorCode == ErrorCodeNone) {
            title = @"Info message";
            message = @"Your new password have been sent to the email, please check and try login again";
        }
        else {
            title = @"Error message";
            message = @"That email you have been entered don't existed in system.";
        }
        alertView = [[UIAlertView alloc] initWithTitle:title
                                               message:message
                                              delegate:nil
                                     cancelButtonTitle:@"OK"
                                     otherButtonTitles:nil];
        [alertView show];
        [alertView release];        
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    [[GruphotoAppDelegate sharedDelegate] hideHUD];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Connection error"
                                                        message:@"Internet is down, please try again"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
    [alertView show];
    [alertView release];
}

@end
